package com.dsl.dslallinone.controller;

import com.dsl.dslallinone.common.ApiResponse;
import com.dsl.dslallinone.dto.DslQuery;
import com.dsl.dslallinone.dto.ExportResult;
import com.dsl.dslallinone.service.ExportService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 导出控制器
 */
@Tag(name = "数据导出", description = "数据导出相关接口")
@RestController
@RequestMapping("/api/dsl/export")
public class ExportController {
    private static final Logger logger = LoggerFactory.getLogger(ExportController.class);

    @Autowired
    private ExportService exportService;

    /**
     * 导出CSV
     */
    @Operation(
            summary = "导出CSV文件",
            description = "将查询结果导出为CSV格式文件，支持最大10万行数据同步导出"
    )
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "导出成功，返回CSV文件",
                    content = @Content(mediaType = "text/csv")
            ),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "数据量过大或参数错误",
                    content = @Content(mediaType = "application/json")
            )
    })
    @PostMapping("/csv")
    public ResponseEntity<?> exportCsv(
            @Parameter(description = "DSL查询请求参数", required = true)
            @Valid @RequestBody DslQuery query) {
        logger.info("开始导出CSV");

        ExportResult result = exportService.exportToCsv(query);
        
        if (result.isSuccess()) {
            Resource resource = result.getResource();
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + result.getFileName() + "\"")
                    .contentType(MediaType.parseMediaType("text/csv"))
                    .body(resource);
        } else {
            return ResponseEntity.ok(ApiResponse.error(400, result.getMessage()));
        }
    }

    /**
     * 导出Excel
     */
    @Operation(
            summary = "导出Excel文件",
            description = "将查询结果导出为Excel格式文件，支持最大10万行数据同步导出"
    )
    @ApiResponses(value = {
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "200",
                    description = "导出成功，返回Excel文件",
                    content = @Content(mediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            ),
            @io.swagger.v3.oas.annotations.responses.ApiResponse(
                    responseCode = "400",
                    description = "数据量过大或参数错误",
                    content = @Content(mediaType = "application/json")
            )
    })
    @PostMapping("/xlsx")
    public ResponseEntity<?> exportXlsx(
            @Parameter(description = "DSL查询请求参数", required = true)
            @Valid @RequestBody DslQuery query) {
        logger.info("开始导出Excel");

        ExportResult result = exportService.exportToXlsx(query);
        
        if (result.isSuccess()) {
            Resource resource = result.getResource();
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + result.getFileName() + "\"")
                    .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
                    .body(resource);
        } else {
            return ResponseEntity.ok(ApiResponse.error(400, result.getMessage()));
        }
    }
}
